/*!
 * vinculum
 * Copyright(c) 2017 azzly
 * MIT Licensed
 */
 
'use strict';

/**
 * Module dependencies.
 * @private
 */
const mysql = require('mysql');
const error = require('./HTTPErrors');
const debug = require("./debug")(__filename);


/**
 * Variables
 * @private
 */

class db{
  constructor(option){
		this.setConnectOption(option);
		this.hasinited = false;
		this.init();
  }
	
	setConnectOption(option = {}){
		this.option = option;
		if(!this.option.climit) {
			this.option.connectionLimit = 10;
		}else{
			this.option.connectionLimit = this.option.climit;
		}
		if(!this.option.host) this.option.host = 'localhost';
		if(!this.option.user) this.option.user = 'root';
		if(!this.option.password) this.option.password = '';
		if(!this.option.database) this.option.database = 'mysql';
	}
	
	init(){
		if(!this.hasinited){
			this._db  = mysql.createPool(this.option);
			this.hasinited = true;
		}
	}
	
	end(){
		if(this.hasinited && this._db){
			this._db.end(err=>{});
			this.hasinited = false;
			this._db = null;
		}
	}
  
  query(...args){
		if(this.hasinited){
			return new Promise((resolve, reject)=>{
				this._db.getConnection((err, connection)=>{
						if(err){
							reject(error.DATABASE_CANNOT_GET_CONNECTION);
						}else{
							connection.query(...args,(err, rows)=>{
								if(err){
									console.error(...args);
									console.error(err);
									reject(error.DATABASE_QUERY_SQL_ERROR);
								}else{
									resolve(rows);
								}
								connection.release();
							});
						}
				});
			});
		}else{
			return Promise.reject(error.DATABASE_NOT_INITED);
		}
  }
}

module.exports = db;